package com.lilingguo.easyserver.controller;

import com.lilingguo.easyserver.container.Container;
import com.lilingguo.easyserver.pojo.ServiceInfo;
import com.lilingguo.easyserver.pojo.ServiceListInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 处理后台控制页面的请求
 *
 * @Author: 黎铃果
 * @Date: 2020/05/28 16:35
 */
@RestController
@RequestMapping("/dashboard")
public class DashboardController {

    @Autowired
    private Container container;

    @GetMapping("/getAllServerList")
    public Object getAllServerList() {
        // serverInfos -- set
        Set<ServiceInfo> data = container.getAllData();
        // serverListInfos -- list
        List<ServiceListInfo> list = new ArrayList<ServiceListInfo>();
        // <name, index of list>
        HashMap<String, Integer> nameMap = new HashMap<String, Integer>(128);

        for (ServiceInfo info : data) {
            ServiceListInfo listInfo;
            String name = info.getName();
            if (nameMap.containsKey(name)) {
                Integer index = nameMap.get(name);
                listInfo = list.get(index);
            } else {
                // save index of list
                nameMap.put(name, list.size());
                listInfo = new ServiceListInfo();
                listInfo.setServiceName(name);
                listInfo.setServiceInfos(new ArrayList<ServiceInfo>());
                list.add(listInfo);
            }
            // server status
            if (info.getStatus() == null) {
                if (info.getTtl() > 0) {
                    info.setStatus(0);
                } else {
                    info.setStatus(1);
                }
            }
            // total count
            listInfo.setTotalCount(listInfo.getTotalCount() + 1);
            // valid count
            if (info.getStatus() == 0) {
                listInfo.setValidCount(listInfo.getValidCount() + 1);
            }
            // add serverInfo
            List<ServiceInfo> infos = listInfo.getServiceInfos();
            infos.add(info);
        }
        for (ServiceListInfo listInfo : list) {
            int totalCount = listInfo.getTotalCount();
            int validCount = listInfo.getValidCount();
            int status = 1;
            if (validCount == 0) {
                status = 2;
            } else if (validCount == totalCount) {
                status = 0;
            }
            listInfo.setStatus(status);
        }
        return list;
    }

}
